package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.DeviceDto;
import com.zzyl.dto.DevicePageQueryDto;
import com.zzyl.entity.Device;
import com.zzyl.enums.BasicEnum;
import com.zzyl.enums.DeviceLocationTypeEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.properties.AliIoTConfigProperties;
import com.zzyl.service.DeviceService;
import com.zzyl.vo.DeviceVo;
import com.zzyl.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description DeviceServiceImpl
 * @Author cuijian
 * @Date 2024-09-12
 */
@Service
@Slf4j
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;
    @Autowired
    private Client client;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //1.远程调用IOT查询所有产品列表接口
        //构造请求对象封装请求参数（CurrentPage，PageSize，IotInstanceId）
        QueryProductListRequest request = new QueryProductListRequest();
        request.setCurrentPage(1);
        request.setPageSize(200);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //执行远程调用获取返回结果
        QueryProductListResponse response;
        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用IOT查询产品列表接口异常", e.getMessage());
            throw new BaseException(BasicEnum.IOT_QUERY_PRODUCT_ERROR);
        }
        //判断接口调用是否成功
        if (!response.getBody().getSuccess()) {
            log.error("调用IOT查询产品列表接口失败");
            throw new BaseException(BasicEnum.IOT_QUERY_PRODUCT_ERROR);
        }

        //2.对返回结果解析(返回数据：data.List.ProductInfo[])封装给List<ProductVo>
        List<ProductVo> productVoList = BeanUtil.copyToList
                (response.getBody().getData().getList().getProductInfo(),
                        ProductVo.class);
        //3.写入缓存
        //定义key
        String key = CacheConstants.ALL_PRODUCT_KEY;
        //写入
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(productVoList), 24, TimeUnit.HOURS);
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //1.从缓存中获取产品列表
        String json = (String) redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        //2.判断缓存中是否有数据
        if (StrUtil.isEmpty(json)) {
            return Collections.emptyList();
        }
        //3.json字符串是否有效,转化为List<ProductVo>
        List<ProductVo> productVoList = JSONUtil.toList(json, ProductVo.class);
        //4.返回数据
        return productVoList;
    }

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 注册设备
     *
     * @param deviceDto
     * @return
     */
    @Override
    public ResponseResult registerDevice(DeviceDto deviceDto) {
        //1.判断新增的设备名称是否重复
        //1.1 根据设备名称查询指定设备数量
        Integer count = deviceMapper.countByDeviceName(deviceDto.getDeviceName());
        //1.2 判断设备数据是否大于0，大于0说明存在，抛出异常注册设备失败
        if (count > 0) {
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }
        //2.调用阿里云IOT远程接口注册设备（接口名字：RegisterDevice）
        //2.1 完善请求对象IotInstanceId属性，请求对象 RegisterDeviceRequest(前端已经传递封装了 ProductKey，DeviceName，Nickname)
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //2.2 执行接口
        RegisterDeviceResponse registerDeviceReponse;
        try {
            registerDeviceReponse = client.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
            e.printStackTrace();//打印控制台完整堆栈信息
            log.error("注册设备失败：{}", e.getMessage());
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }
        //2.3 判断远程接口调用是否成功（Success属性）
        if (!registerDeviceReponse.getBody().getSuccess()) {
            log.error("注册设备失败：{}");
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }
        //2.4 定义变量接收物联网设备的id
        String iotId = registerDeviceReponse.getBody().getData().getIotId();
        //3.调用阿里云IOT远程接口查询产品详情（QueryProduct）
        //3.1 封装请求对象 手动封装QueryProductRequest(ProductKey,IotInstanceId)
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setProductKey(deviceDto.getProductKey());
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //3.2 执行接口
        QueryProductResponse queryProductResponse;
        try {
            queryProductResponse = client.queryProduct(queryProductRequest);
        } catch (Exception e) {
            e.printStackTrace();//打印控制台完整堆栈信息
            log.error("查询产品详情失败：{}", e.getMessage());
            throw new BaseException(BasicEnum.IOT_QUERY_PRODUCT_ERROR);
        }
        //3.3 判断远程接口调用是否成功（Success属性）
        if (!queryProductResponse.getBody().getSuccess()) {
            log.error("查询产品详情失败：{}");
            throw new BaseException(BasicEnum.IOT_QUERY_PRODUCT_ERROR);
        }
        //3.4 定义变量接收 产品名字
        String productName = queryProductResponse.getBody().getData().getProductName();
        //4.判断位置类型是否是绑定随身设备
        //4.1 是，设置物理位置类型为-
        if (deviceDto.getLocationType().equals(DeviceLocationTypeEnum.PORTABLE_DEVICE.getOrdinal())) {
            deviceDto.setPhysicalLocationType(-1);
        }
        //5.将设备数据插入数据库
        //5.0将设备数据封装成实体类
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //5.1 完善数据，设置没有门禁为0
        device.setHaveEntranceGuard(0);
        //5.2 完善数据，封装产品名字
        device.setProductName(productName);
        //5.3 完善数据，封装设备id
        device.setIotId(iotId);
        try {
            //5.4 插入数据库
            deviceMapper.insertSelective(device);
        } catch (Exception e) {
            //5.5 插入失败（发生异常），调用阿里云IOT远程接口删除设备（DeleteDevice）
            //5.5.1 封装请求对象DeleteDeviceRequest(IotInstanceId,IotId)
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            deleteDeviceRequest.setIotId(iotId);
            try {
                //5.5.2执行接口
                client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                log.error("删除设备失败：{}");
                throw new BaseException(BasicEnum.IOT_DELETE_DEVICE_ERROR);
            }
        }
        //6.返回成功
        return ResponseResult.success();
    }

    /**
     * 分页查询
     *
     * @param devicePageQueryDto
     */
    @Override
    public PageResponse<DeviceVo> pageQueryDevice(DevicePageQueryDto devicePageQueryDto) {

        PageHelper.startPage(devicePageQueryDto.getPageNum(), devicePageQueryDto.getPageSize());
        Page<DeviceVo> deviceVos = deviceMapper.selectByPage(devicePageQueryDto);
        return PageResponse.of(deviceVos, DeviceVo.class);

    }

    /**
     * 查询设备详情
     *
     * @param request
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(QueryDeviceDetailRequest request) {
        //1.调用iot查询设备详情接口获取详情数据
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //1.2执行接口
        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            log.error("查询设备详情失败：{}", e.getMessage());
            throw new BaseException(BasicEnum.IOT_QUERY_PRODUCT_ERROR);
        }
        if (!response.getBody().getSuccess()) {
            throw new BaseException(BasicEnum.IOT_QUERY_PRODUCT_ERROR);
        }
        //1.3获取详情数据
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData deviceDetailData = response.getBody().getData();
        //2.调用mapper根据设备id查询数据库数据DeviceVo
        DeviceVo deviceVo = deviceMapper.findByDeviceId(deviceDetailData.getIotId());
        //3.将IoT详情数据与数据库数据的DeviceVo合并返回
        BeanUtil.copyProperties(deviceDetailData, deviceVo, CopyOptions.create().ignoreNullValue());//dateDetail有赋值给deviceVo,没有值不赋值
        //4.返回数据
        return deviceVo;
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param request
     * @return
     */
    @Override
    public ResponseResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        //1.调用iot查询设备详情接口获取详情数据
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //2执行接口
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.IOT_QUERY_DEVICE_PROPERTY_STATUS_ERROR);
        }
        return ResponseResult.success(response.getBody().getData());
    }


    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param request
     * @return
     */
    @Override
    public ResponseResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        //1.调用iot查询设备详情接口获取详情数据
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //2执行接口
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.IOT_QUERY_THING_MODEL_PUBLISHED_ERROR);

        }
        return ResponseResult.success(response.getBody().getData());
    }

    /**
     * 更新设备信息
     *
     * @param deviceDto
     */
    @Override
    public void updateDevice(DeviceDto deviceDto) {

    }

    /**
     * 删除设备
     * @param request
     */
    @Override
    public void deleteDevice(DeleteDeviceRequest request) {
        //1.调用iot查询设备详情接口获取详情数据
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //2执行接口
        DeleteDeviceResponse response;
        //3.判断是否删除成功
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.IOT_DELETE_DEVICE_ERROR);
        }
        if (Boolean.TRUE.equals(response.getBody().getSuccess())) {
            //3.1删除成功，调用mapper根据设备id删除数据库数据
            deviceMapper.deleteByIotId(request.getIotId());
            return;
        }
        throw new BaseException(BasicEnum.IOT_DELETE_DEVICE_ERROR);
    }

}

